package controllers;

import models.forms.IndexForm;
import play.data.Form;
import play.mvc.*;
import tp.badugi.net.ServerNetworkingChannel;
import tp.badugi.server.Table;
import views.html.*;

@org.springframework.stereotype.Controller
public class Application extends Controller {
	
	private Table table;
	
	public Application() {
		table = new Table();
	}
	
	public Application(Table table) {
		this.table = table;
	}
	
    public Result index() {
        return ok(index.render("Your new application is ready."));
    }
    
    public Result indexBadugi(){
    	return ok(indexBadugi.render());
    }
    
    public Result indexSubmit(String userName){
    	
    	if(userName == null || userName.trim().equals("")) {
            flash("error", "Please choose a valid username.");
            return redirect(routes.Application.indexBadugi());
        }
        return ok(gameRoom.render(userName));
    }
    
    public Result socketJs(String username) {
    	return ok(views.js.socket.render(username));
    }
    
    public WebSocket<String> socket(final String username) {
        return new WebSocket<String>() {

        	// Called when the Websocket Handshake is done.
        	@Override
            public void onReady(WebSocket.In<String> in, WebSocket.Out<String> out){
        		
        		ServerNetworkingChannel netChannel = new ServerNetworkingChannel(in, out);
				
                // Join the table.
                try {
                	table.addPlayer(username, netChannel);
                } 
                catch (Exception ex) {
                    ex.printStackTrace();
                }
            }

        };
    }

}
